<template>
  <div class="login-form">
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      @submit.prevent="handleSubmit"
    >
      <!-- 账号输入 -->
      <el-form-item prop="account">
        <el-input
          v-model="form.account"
          :placeholder="$t('auth.enterAccount')"
          prefix-icon="User"
          size="large"
          clearable
        />
      </el-form-item>

      <!-- 密码输入 -->
      <el-form-item prop="password">
        <el-input
          v-model="form.password"
          type="password"
          :placeholder="$t('auth.enterPassword')"
          prefix-icon="Lock"
          show-password
          size="large"
          clearable
        />
      </el-form-item>

      <!-- 记住我 & 忘记密码 -->
      <div class="form-options">
        <el-checkbox v-model="form.rememberMe">{{ $t('auth.rememberMe') }}</el-checkbox>
        <el-button link @click="handleForgotPassword">
          {{ $t('auth.forgotPassword') }}
        </el-button>
      </div>
      
      <!-- 服务条款和隐私条款 -->
      <el-form-item prop="agreeTerms">
        <el-checkbox v-model="form.agreeTerms">
          我已阅读并同意
          <el-button link @click.prevent="openTerms('service')">用户服务条款</el-button>
          和
          <el-button link @click.prevent="openTerms('privacy')">隐私条款</el-button>
        </el-checkbox>
      </el-form-item>

      <!-- 提交按钮 -->
      <el-form-item>
        <el-button
          type="primary"
          native-type="submit"
          :loading="loading"
          class="submit-btn"
        >
          {{ $t('auth.login') }}
        </el-button>
      </el-form-item>

      <!-- 第三方登录 -->
      <!-- <div class="third-party-login">
        <div class="divider">
          <span>{{ $t('auth.orLoginWith') }}</span>
        </div>
        <div class="third-party-buttons">
          <el-button circle>
            <el-icon><i-ep-position /></el-icon>
          </el-button>
          <el-button circle>
            <el-icon><i-ep-chat-dot-round /></el-icon>
          </el-button>
          <el-button circle>
            <el-icon><i-ep-phone /></el-icon>
          </el-button>
        </div>
      </div> -->

      <!-- 注册链接 -->
      <div class="register-link">
        {{ $t('auth.noAccount') }}
        <el-button link @click="$emit('switch-mode')">
          {{ $t('auth.register') }}
        </el-button>
      </div>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage} from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';
import { useUserStore } from '@/store/user';

const emit = defineEmits(['switch-mode', 'open-terms', 'login-success']);
const router = useRouter();
const userStore = useUserStore();
const formRef = ref<FormInstance>();
const loading = ref(false);

// 表单数据
const form = reactive({
  account: '',
  password: '',
  rememberMe: false,
  agreeTerms: false
});

// 表单验证规则
const rules: FormRules = {
  account: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { min: 3, message: '账号长度不能小于3个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6个字符', trigger: 'blur' }
  ],
  agreeTerms: [
    { 
      validator: (_, value, callback) => {
        if (!value) {
          callback(new Error('请同意用户服务条款和隐私条款'));
        } else {
          callback();
        }
      },
      trigger: 'change'
    }
  ]
};

// 打开条款对话框
const openTerms = (type: string) => {
  emit('open-terms', type);
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      if (!form.agreeTerms) {
        ElMessage.error('请同意用户服务条款和隐私条款');
        return;
      }
      
      loading.value = true;
      
      try {
        await userStore.login({
          account: form.account,
          password: form.password,
          rememberMe: form.rememberMe
        });
        
        ElMessage.success('登录成功');
        
        // 通知父组件登录成功，关闭弹窗
        emit('login-success');
        
        // 如果有重定向地址，则跳转到重定向地址
        const redirect = router.currentRoute.value.query.redirect as string;
        if (redirect) {
          router.push(redirect);
        }
      } catch (error: any) {
        ElMessage.error(error.message || '登录失败，请检查账号和密码');
      } finally {
        loading.value = false;
      }
    }
  });
};

// 忘记密码
const handleForgotPassword = () => {
  router.push('/forgot-password');
};
</script>

<style scoped lang="scss">
.login-form {
  :deep(.el-form-item) {
    margin-bottom: 18px;  // 减小表单项之间的间距
  }

  .form-options {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: -10px 0 18px 0;
  }
  
  :deep(.el-checkbox__label) {
    color: #606266;
  }

  .submit-btn {
    width: 100%;
    height: 40px;  // 增加按钮高度
    font-size: 16px;  // 增大按钮文字
  }
  
  .third-party-login {
    margin-top: 24px;
    
    .divider {
      display: flex;
      align-items: center;
      margin: 20px 0;
      
      &::before,
      &::after {
        content: '';
        flex: 1;
        border-top: 1px solid #dcdfe6;
      }
      
      span {
        padding: 0 12px;
        color: #909399;
        font-size: 14px;
      }
    }
    
    .third-party-buttons {
      display: flex;
      justify-content: center;
      gap: 24px;
      margin-bottom: 20px;

      .el-button {
        width: 40px;
        height: 40px;
        padding: 8px;
        border-color: #dcdfe6;
        
        &:hover {
          background-color: #f5f7fa;
        }
      }
    }
  }
  
  .register-link {
    text-align: center;
    margin-top: 16px;
    color: #606266;
    font-size: 14px;

    .el-button {
      padding: 0 4px;
      font-size: 14px;
      font-weight: 500;
    }
  }
}
</style>